<?php

namespace App\Services;
use App\Models\User;
use App\Repositories\Contract\UserRelationRepository;
use App\Services\Contract\UserRelationServiceInterface;

class UserRelationService  extends AbstractService implements UserRelationServiceInterface{

    protected $userRelation;

    public function __construct(UserRelationRepository $userRelation)
    {
        $this->userRelation = $userRelation;
    }

    function paginate(array $query, int $pageSize)
    {
        $data =  $this->userRelation->scopeQuery(function ($builder) use ($query) {
            return $builder->where($query);
        })->orderBy('created_at', 'DESC')->paginate($pageSize);
        //清洗数据
        $lastData = [];
        foreach($data as $one){
            $o = [];
            $o['id'] = $one->id;
            $o['friend_name'] = $one->user->name;
            $o['friend_email'] = $one->user->email;
            $o['created_at'] = $one->created_at;
            $lastData[] = $o;
        }
        return $lastData;
    }

    public function create($post)
    {
        $email = $post['email'];
        $user = User::where(['email' => $email])->first();
        if(!$user){
            $this->error = '用户未找到';
            return null;
        }
        $post['friend_id'] = $user->id;
        return $this->userRelation->create($post);
    }
}
